package com.bluefuture.modules.app.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.bluefuture.common.utils.IosVerifyUtil;
import com.bluefuture.common.utils.ResultEnum;
import com.bluefuture.common.utils.ResultVo;
import com.bluefuture.common.utils.ResultVoUtil;
import com.bluefuture.modules.app.entity.AppOrderEntity;
import com.bluefuture.modules.app.entity.UserEntity;
import com.bluefuture.modules.app.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.bluefuture.common.utils.ResultEnum.RECEIPT_DATA_ERROR;

/**
 * @Author: leo
 * @date: 2022/1/29
 */
@Service("iosService")
@Slf4j
public class IosServiceImpl {

    @Autowired
    private AppOrderServiceImpl appOrderService;
    @Autowired
    private UserService userService;

    public static void main(String[] args) {
//        IosServiceImpl iosService = new IosServiceImpl();
//        ResultVo resultVo = iosService.iosInAppPurchase("1", "ewoJInNpZ25hdHVyZSIgPSAiQW5USlN6UUFqZWhXWW1ucWxvZk9ZVnFyWEo1MVVOWnI5Ly8ySFhxM01COWkyYVBqVmlsdjM4aXhtWm9PLzlZZlBsUkhZRHVzWFQySXBZYkRzNHBGWk53L21RTDFUemtJSWV0WWVhNE95anVWNUtsdUVCNExLVm9sN25tSGZkMjdISTZQTTZqQkRaS0xtcGt0bU5WQ21mbmhlVCtqbE1qTHg3ZVpLakhTRmhsUkFBQURWekNDQTFNd2dnSTdvQU1DQVFJQ0NCdXA0K1BBaG0vTE1BMEdDU3FHU0liM0RRRUJCUVVBTUg4eEN6QUpCZ05WQkFZVEFsVlRNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVNZd0pBWURWUVFMREIxQmNIQnNaU0JEWlhKMGFXWnBZMkYwYVc5dUlFRjFkR2h2Y21sMGVURXpNREVHQTFVRUF3d3FRWEJ3YkdVZ2F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OUlDSTBSVFZGTVVFelFpMUdNREZCTFRRNE5UVXRPREl3UmkxR016UTVSakV5TkRJeE5EZ2lPd29KSW1WNGNHbHlaWE10WkdGMFpTMW1iM0p0WVhSMFpXUXRjSE4wSWlBOUlDSXlNREUxTFRFeExUSXpJREl5T2pNME9qUXhJRUZ0WlhKcFkyRXZURzl6WDBGdVoyVnNaWE1pT3dvSkltbDBaVzB0YVdRaUlEMGdJakV3TWpnNU5UQTNPVGNpT3dvSkltVjRjR2x5WlhNdFpHRjBaUzFtYjNKdFlYUjBaV1FpSUQwZ0lqSXdNVFV0TVRFdE1qUWdNRFk2TXpRNk5ERWdSWFJqTDBkTlZDSTdDZ2tpY0hKdlpIVmpkQzFwWkNJZ1BTQWllV1ZoY214NUlqc0tDU0p3ZFhKamFHRnpaUzFrWVhSbElpQTlJQ0l5TURFMUxURXhMVEU0SURBME9qTTBPalF4SUVWMFl5OUhUVlFpT3dvSkltOXlhV2RwYm1Gc0xYQjFjbU5vWVhObExXUmhkR1VpSUQwZ0lqSXdNVFV0TVRFdE1UY2dNVFk2TXpRNk5ERWdSWFJqTDBkTlZDSTdDZ2tpWW1sa0lpQTlJQ0pqYjIwdWJXSmhZWE41TG1sdmN5NWtaVzF2SWpzS0NTSndkWEpqYUdGelpTMWtZWFJsTFhCemRDSWdQU0FpTWpBeE5TMHhNUzB4TnlBeU1Eb3pORG8wTVNCQmJXVnlhV05oTDB4dmMxOUJibWRsYkdWeklqc0tDU0p4ZFdGdWRHbDBlU0lnUFNBaU1TSTdDbjA9IjsKCSJlbnZpcm9ubWVudCIgPSAiU2FuZGJveCI7CgkicG9kIiA9ICIxMDAiOwoJInNpZ25pbmctc3RhdHVzIiA9ICIwIjsKfQ==");
//        System.out.println(resultVo);
    }

    public ResultVo iosInAppPurchase(AppOrderEntity appOrderEntity) {
        if (StringUtils.isNotBlank(appOrderEntity.getOrderNo())){
            UserEntity userEntity = userService.getById(appOrderEntity.getUserId());
            if (userEntity!=null){
                userEntity.setMembershipType(4);
                userEntity.setUpdateTime(new Date());
                userService.updateById(userEntity);
            }
            return ResultVoUtil.success();
        }

        String productId = appOrderEntity.getOrderNo();
        String receipt = appOrderEntity.getSeq();
        String verifyResult = IosVerifyUtil.buyAppVerify(receipt, 1);
        if (StringUtils.isBlank(verifyResult)) {// 苹果服务器没有返回验证结果
            log.info("IOS内购(充值)=>苹果服务器没有返回验证结果");
            return ResultVoUtil.error(ResultEnum.IOS_SERVER_NOT_RETURN_ERROR);

        } else {// 苹果验证有返回结果
            JSONObject job = JSONObject.parseObject(verifyResult);
            log.info("IOS内购(充值)=>苹果服务器返回验证结果:{}", job);
            String states = job.getString("status");
            //是沙盒环境，应沙盒测试，否则执行下面
            if ("21007".equals(states)) {
                //2.在沙盒测试  发送平台验证
                verifyResult = IosVerifyUtil.buyAppVerify(receipt, 0);
                job = JSONObject.parseObject(verifyResult);
                states = job.getString("status");
            }
            if (states.equals("0")) { // 前端所提供的收据是有效的    验证成功
                String r_receipt = job.getString("receipt");
                JSONObject returnJson = JSONObject.parseObject(r_receipt);
                String in_app = returnJson.getString("in_app");
                JSONArray jsonArray = JSONArray.parseArray(in_app);
                log.info("IOS内购(充值)=>苹果服务器返回验证结果订单数量:{}", jsonArray.size());
                for (int i = 0; i < jsonArray.size(); i++) {
                    if (productId.equals(jsonArray.getJSONObject(i).get("product_id") == null ? null : jsonArray.getJSONObject(i).get("product_id").toString())) {
                        // 订单号
                        String transactionId = jsonArray.getJSONObject(i).get("transaction_id") == null ? null : jsonArray.getJSONObject(i).get("transaction_id").toString();
                        // 支付时间
                        String purchaseDate = jsonArray.getJSONObject(i).get("purchase_date") == null ? null : jsonArray.getJSONObject(i).get("transaction_id").toString();
                        appOrderEntity.setStatus(2);
                        appOrderEntity.setTransactionId(transactionId);
                        appOrderEntity.setPurchaseDate(new Date(Long.parseLong(purchaseDate)));
                        appOrderService.updateById(appOrderEntity);
                        /* 自己的业务处理 */
                        // 1.创建订单信息
                        // 2. 增加用户虚拟币数量
                        // 3. 添加用户消费记录
                        UserEntity userEntity = userService.getById(appOrderEntity.getUserId());
                        if (userEntity!=null){
                            userEntity.setMembershipType(appOrderEntity.getType()+1);
                            userEntity.setUpdateTime(new Date());
                            userService.updateById(userEntity);
                        }
                    }
                }
            } else {
                return ResultVoUtil.error(RECEIPT_DATA_ERROR);
            }
        }
        return ResultVoUtil.success();
    }
    /**

     * 苹果服务器验证

     *

     * @param receipt

     * 账单

     * @url 要验证的地址

     * @return null 或返回结果 沙盒 https://sandbox.itunes.apple.com/verifyReceipt

     *

     * 21000App Store无法读取你提供的JSON数据

     * 21002 订单数据不符合格式

     * 21003 订单无法被验证

     * 21004 你提供的共享密钥和账户的共享密钥不一致

     * 21005 订单服务器当前不可用

     * 21006 订单是有效的，但订阅服务已经过期。当收到这个信息时，解码后的收据信息也包含在返回内容中

     * 21007 订单信息是测试用(sandbox)，但却被发送到产品环境中验证

     * 21008 订单信息是产品环境中使用，但却被发送到测试环境中验证

     */
}
